<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background-color: rgb(98, 159, 184);
            overflow: hidden;
            position: absolute;
            left: 100px;
            top: 100px;
        }
        .active{
            z-index: 999;
        }
    </style>
</head>
<body>
    <button class="back">back</button>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</body>
<script>

// 构造函数
    

    Drag.prototype.init =  function() {   
 
        // this -> 调用此方法的实例化对象
        this.randColor();
        this.dragStart();
    }

    Drag.prototype.dragStart = function() {
        this.target.onmousedown = (e) => { 
            var e = e || window.event;

            var posX = e.offsetX;
            var posY = e.offsetY;
            this.posX = posX;
            this.posY = posY;

            this.target.classList.add("active");

            this.dragMove()    // 先按下再移动
            this.dragEnd()     // 按下时绑定抬起                   
            
        }
    }
   
    Drag.prototype.dragMove = function() {
        document.onmousemove = (e) => {
            var e = e || window.event;

            var x = e.pageX -  this.posX;
            var y = e.pageY -  this.posY;
            this.target.style.left = x + "px";
            this.target.style.top = y + "px";

        }
    }
    
    Drag.prototype.dragEnd = function(){
        document.onmouseup = () => {
            var e = e || window.event;
            document.onmousemove = null;
            document.onmousedown = null;
            this.target.classList.remove("active")
        }
    }

    Drag.prototype.randColor = function(){
        this.target.style.backgroundColor = `rgb(${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)})`;
    }
 

    function Drag(ele) {
        this.target = ele;
        this.init();         // 初始化操作   => 每次调用构造函数之后 =>实例化  => 默认执行一些方法

    }
    console.dir(Drag);
  
    var boxList = document.getElementsByClassName("box");   // 拖拽的元素
    for(let i = 0; i < boxList.length; i++) {
        let box = boxList[i];
        let obj = new Drag(box);
        console.log(obj);        
    }

  
    
    
</script>
</html>